package jq.core.text;

public class TextUtil {
	private int startIndex;
	private int endIndex;
	private String content;

	public int getStartIndex() {
		return startIndex;
	}

	public void setStartIndex(int startIndex) {
		this.startIndex = startIndex;
	}

	public int getEndIndex() {
		return endIndex;
	}

	public void setEndIndex(int endIndex) {
		this.endIndex = endIndex;
	}

	public TextUtil(String content) {
		super();
		this.startIndex = 0;
		this.endIndex = content.length();
		this.content = content;
	}

	public boolean selectText(String startFlag, String endFlag) {
		int fromIndex = content.indexOf(startFlag, startIndex);
		if (fromIndex == -1) {
			return false;
		}
		int termIndex = content.indexOf(endFlag, fromIndex + startFlag.length());
		if (termIndex == -1) {
			return false;
		}
		// set start and end index
		this.startIndex = fromIndex + startFlag.length();
		this.endIndex = termIndex;
		return true;
	}

	public String extractText() {
		return this.content.substring(this.startIndex, this.endIndex);
	}

	public String extractText(String innerStartFlag, String innerEndFlag) {
		if (innerStartFlag == null && innerEndFlag == null) {
			return extractText();
		}
		if (innerStartFlag == null && innerEndFlag != null) {
			int index = this.content.indexOf(innerEndFlag, this.startIndex);
			if (index == -1 || index > this.endIndex) {
				return "";
			} else {
				return this.content.substring(this.startIndex, index);
			}
		}
		if (innerStartFlag != null && innerEndFlag == null) {
			int index = this.content.indexOf(innerStartFlag, this.startIndex);
			if (index == -1 || index > this.endIndex) {
				return "";
			} else {
				return this.content.substring(index + innerStartFlag.length(), endIndex);
			}
		}
		// if they are all specified
		int inf = this.content.indexOf(innerStartFlag, this.startIndex);
		int ine = this.content.indexOf(innerEndFlag, this.startIndex);
		if (inf == -1 || ine == -1 || inf > ine || inf > this.endIndex || ine > this.endIndex) {
			return "";
		} else {
			return this.content.substring(inf + innerStartFlag.length(), ine);
		}
	}

	public void deselectText() {
		this.startIndex=0;
		this.endIndex=this.content.length();
	}
}
